package client

import (
	intrv1 "bbs-micro/api/proto/gen/proto/intr/v1"
	"bbs-micro/bbs-bff/internal/domain"
	"bbs-micro/bbs-bff/internal/service"
	"context"
	"google.golang.org/grpc"
)

// @Description  适配器流量分发
// @Author 代码小学生王木木
// @Date 2024-04-11 15:45

// 实现 intrv1.InteractiveServiceClient 这个接口

//适配器模式，demo，继承这个接口要实现这个接口的所有的方法

// InteractiveServiceServer
// @Description: 将一个本地的实现 伪装为GPRC客户端
type InteractiveServiceAdapter struct {
	svc service.InteractiveService
}

func NewInteractiveServiceAdapter(svc service.InteractiveService) *InteractiveServiceAdapter {
	return &InteractiveServiceAdapter{
		svc: svc,
	}
}

func (i *InteractiveServiceAdapter) IncrReadCnt(ctx context.Context, request *intrv1.IncrReadCntRequest, opt ...grpc.CallOption) (*intrv1.IncrReadCntResponse, error) {
	err := i.svc.IncrReadCnt(ctx, request.GetBiz(), request.GetBizId())
	if err != nil {
		return nil, err
	}
	return &intrv1.IncrReadCntResponse{}, nil

}

func (i *InteractiveServiceAdapter) Like(ctx context.Context, request *intrv1.LikeRequest, opt ...grpc.CallOption) (*intrv1.LikeResponse, error) {
	err := i.svc.Like(ctx, request.GetBiz(), request.GetBizId(), request.GetUid())
	if err != nil {
		return nil, err
	}
	return &intrv1.LikeResponse{}, nil
}

func (i *InteractiveServiceAdapter) CancelLike(ctx context.Context, request *intrv1.CancelLikeRequest, opt ...grpc.CallOption) (*intrv1.CancelLikeResponse, error) {
	err := i.svc.CancelLike(ctx, request.GetBiz(), request.GetBizId(), request.GetUid())
	if err != nil {
		return nil, err
	}
	return &intrv1.CancelLikeResponse{}, nil
}

func (i *InteractiveServiceAdapter) CollectArt(ctx context.Context, in *intrv1.CollectArtRequest, opts ...grpc.CallOption) (*intrv1.CollectArtResponse, error) {
	err := i.svc.CollectArt(ctx, in.GetBiz(), in.GetBizId(), in.GetUid(), in.GetCid())
	return &intrv1.CollectArtResponse{}, err
}

func (i *InteractiveServiceAdapter) Get(ctx context.Context, request *intrv1.GetRequest, opt ...grpc.CallOption) (*intrv1.GetResponse, error) {
	get, err := i.svc.Get(ctx, request.GetBiz(), request.GetBizId(), request.GetUid())
	if err != nil {
		return nil, err
	}
	return &intrv1.GetResponse{
		Intr: i.toDTO(get),
	}, nil
}

func (i *InteractiveServiceAdapter) GetByIds(ctx context.Context, request *intrv1.GetByIdsRequest, opt ...grpc.CallOption) (*intrv1.GetByIdsResponse, error) {
	ids, err := i.svc.GetByIds(ctx, request.GetBiz(), request.GetIds())
	if err != nil {
		return nil, err
	}
	m := make(map[int64]*intrv1.Interactive, len(ids))
	for k, v := range ids {
		m[k] = i.toDTO(v)
	}
	return &intrv1.GetByIdsResponse{Intrs: m}, nil
}

func (i *InteractiveServiceAdapter) toDTO(item domain.Interactive) *intrv1.Interactive {
	return &intrv1.Interactive{
		Biz:        item.Biz,
		BizId:      item.BizId,
		ReadCnt:    item.ReadCnt,
		LikeCnt:    item.LikeCnt,
		CollectCnt: item.CollectCnt,
		CommentCnt: item.CommentCnt,
		Liked:      item.Liked,
		Collected:  item.Collected,
	}
}
